#include <regex.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

void regerror_test1()
{
  char errbuf[512];
  regex_t re;

  // This regex is invalid, regcomp should fail.
  int i = regcomp(&re, "hello([0-9]*)world", REG_EXTENDED);
  //fprintf(stdout, "i = %d\n", i);
  assert (i==0);
  // Get the failure error message
  regerror(i,&re,errbuf,sizeof(errbuf));
  printf("(expected) regcomp error string: %s\n", errbuf);
}

void regex_match_test2()
{
  regex_t re;
  regmatch_t matches[10];

   // const char *RegEx = "(zone.)(\\S+):(.*?);(\\S+)";  const char *Data = "zone.VIOS_P730B_SC8KDISK:SC8K_VIR;VIOS_P730B";
    //const char *RegEx = "zone.([^:]*)";  const char *Data = "zone.hs22_4_md3620f:20:12:f0:1f:af:d5:c3:9d;20:23:f0:1f:af:d5:c3:9d;21:00:00:24:ff:52:99:04";
  const char *RegEx = "zone.([^:]+):(\\S+)"; 
  const char *Data = "zone.m1000e0slot4_md3620f:20:12:f0:1f:af:d5:c3:9d;20:23:f0:1f:af:d5:c3:9d;m1000e0_slot4";

  int i = regcomp(&re, RegEx, REG_EXTENDED);
  assert(i==0);
  //fprintf(stdout, "re_nsub=%d\n", re.re_nsub);
  i = regexec(&re, Data,
              sizeof(matches)/sizeof(matches[0]),
              (regmatch_t*)&matches,0);
  assert(i == 0);

#if 0
  // Extract it
  int idx = 0;  //1st. Full match
  char *val = strndup(data+matches[idx].rm_so,
                      matches[idx].rm_eo - matches[idx].rm_so);
    fprintf(stdout, "val -> %s\n", val);  free(val);

  idx = 1;      //2nd. $1
  val = strndup(data+matches[idx].rm_so,
                      matches[idx].rm_eo - matches[idx].rm_so);
    fprintf(stdout, "val -> %s\n", val);  free(val);

  idx = 2;      //3rd. ;
  val = strndup(data+matches[idx].rm_so,
                      matches[idx].rm_eo - matches[idx].rm_so);
    fprintf(stdout, "val -> %s\n", val);  free(val);

  idx = 3;      //4th. $2
  val = strndup(data+matches[idx].rm_so,
                      matches[idx].rm_eo - matches[idx].rm_so);
    fprintf(stdout, "val -> %s\n", val);  free(val);

  idx = 4;      //5th. Null
  val = strndup(data+matches[idx].rm_so,
                      matches[idx].rm_eo - matches[idx].rm_so);
    fprintf(stdout, "val -> %s\n", val);  free(val);
#endif

    for(int idx = 1; idx <= re.re_nsub; idx++)
    {
        char *val = strndup(Data+matches[idx].rm_so,  matches[idx].rm_eo-matches[idx].rm_so);
        fprintf(stdout, "Value[$%d] -> %s\n", idx, val);  
        free(val);
    }
  regfree(&re);
}

int main()
{
  //regerror_test1();
  regex_match_test2();
  return 0;
}